<template>
  <div>
    <n-card class="user-content">
      <!-- 搜索部分 -->
      <n-grid x-gap="24">
        <n-gi span="6">
          <n-input-group>
            <n-input :style="{ width: '100%' }" placeholder="请输入用户名" />
            <n-button type="primary" @click="searchUser">搜索</n-button>
          </n-input-group>
        </n-gi>
        <n-gi span="18">
          <n-space>
            <n-button type="primary" @click="addUser">新建用户</n-button>
            <n-button type="default" style="margin-left: 20px">
              <template #icon>
                <n-icon>
                  <CloudUploadSharp />
                </n-icon>
              </template>
              导 入
            </n-button>
          </n-space>
        </n-gi>
      </n-grid>

      <!-- 用户列表 -->
      <div style="margin-top: 30px">
        <n-data-table
          ref="table"
          :columns="columns"
          :data="data"
          :row-key="(row) => row.id"
          @update:checked-row-keys="handleCheck"
          :loading="false"
        />        
      </div>

      <!-- 底部分页全选 -->
      <n-grid x-gap="24" style="margin-top: 15px; margin-bottom: 15px">
        <!-- 全选按钮 -->
        <n-gi span="4">
          <n-checkbox v-model:checked="checkedAll" @update:checked="handleCheckedChange">全选</n-checkbox>
          <span>已选 {{ checkedRowKeys.length }} 行</span>
        </n-gi>

        <!-- 分页部分 -->
        <n-gi span="20">
          <n-space justify="end">
            <n-pagination
              v-model:page="page"
              v-model:page-size="pageSize"
              :page-count="pageCount"
              show-size-picker
              :page-sizes="pageGroup"
              show-quick-jumper
              @update:page="PageChange"
              @update:page-size="pageSizeChange"
            />
          </n-space>
        </n-gi>
      </n-grid>

      <!-- 弹出对话框 -->
      <n-modal
        class="custom-card"
        v-model:show="showModal"
        preset="card"
        style="width: 600px;"
        header-style="height:50px;font-size:20px"
        :title="modalTitle"
        size="huge"
        :bordered="false"
        :segmented="segmented"
        :mask-closable="false"
      >
        <n-form
          :model="userValue"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="70"
          :style="{
            maxWidth: '640px'
          }"
        >
          <n-form-item label="账号" path="user">
            <n-input placeholder="账号" v-model:value="userValue.user" />
          </n-form-item>

          <n-form-item label="姓名" path="name">
            <n-input placeholder="姓名" v-model:value="userValue.name" />
          </n-form-item>

          <n-form-item label="状态" path="status">
            <n-switch  v-model:value="userValue.status" >
              <template #checked>启用</template>
              <template #unchecked>禁用</template>
            </n-switch>
          </n-form-item>

          <n-form-item label="角色" path="role">
            <n-select
              v-model:value="userValue.role"
              :options="roleOptions"
              @update:value="roleSelected"
            />
          </n-form-item>

          <n-form-item label="电话" path="phone">
            <n-input placeholder="电话" v-model:value="userValue.phone" />
          </n-form-item>

          <n-form-item label="邮箱" path="email">
            <n-input placeholder="邮箱" v-model:value="userValue.email" />
          </n-form-item>

          <n-form-item path="password" label="密码">
            <n-input
              v-model:value="userValue.password"
              placeholder="输入密码"
              @input="handlePasswordInput"
              type="password"
              @keydown.enter.prevent
            />
          </n-form-item>
          <n-form-item first path="reenteredPassword" label="重复密码">
            <n-input
              :disabled="!userValue.password"
              v-model:value="userValue.reenteredPassword"
              placeholder="重复密码"
              type="password"
              @keydown.enter.prevent
            />
          </n-form-item>

          <n-form-item>
            <n-space justify="end" style="width:100%;">
              <n-button @click="cancleBtn">取消</n-button>
              <n-button type="primary" @click="editUser">确认</n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup>
import { CloudUploadSharp } from "@vicons/ionicons5";
import { useMessage, NBadge, NButton, NSpace, NTag, useDialog } from "naive-ui";
import {
  computed,
  getCurrentInstance,
  onBeforeMount,
  ref,
  h,
  toRaw,
} from "vue";

import formateData from "../../utils/formateData";
const { proxy } = getCurrentInstance();

const message = useMessage();
const dialog = useDialog()

// 弹出对话框
const showModal = ref(false)
const modalTitle = ref(null)
const roleValue = ref(null)
const formRef = ref(null)



const stateOption = ref([
  {
    label: "启用",
    value: 1,
  },
  {
    label: "禁用",
    value: 2,
  },
  {
    label: "删除",
    value: 3,
  }
])


// 编辑用户对话框下拉框
function roleSelected(a) {
  console.log(a)
  console.log(userValue.value.role)
}
const segmented = {
  content: 'hard',
}

function userValueInit() {
  return {
    id: 0,
    user: "test",
    name: "test",
    email: "moujunmore@qq.com",
    phone: "13333333333",
    status: true,
    role: 2,
    password: "123456",
    reenteredPassword: "123456",
    createdAt: null,
    updatedAt: null,
    deletedAt: null
  }
}


const userValue = ref(userValueInit())



//自定义校验事件
function validatePasswordStartWith(rule, value) {
  return (
    userValue.value.password &&
    userValue.value.password.startsWith(value) &&
    userValue.value.password.length >= value.length
  )
}
function validatePasswordSame(rule, value) {
  return value === userValue.value.password
}

const rules = {
  user: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值,最短长度为 2', min: 2 }
  ],
  name: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值' }
  ],
  password: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值,最短长度为 5', min: 5 }
  ],
  reenteredPassword: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值,最短长度为 5', min: 5 },
    { validator: validatePasswordStartWith, message: '两次密码输入不一致', trigger: 'input' },
    { validator: validatePasswordSame, message: '两次密码输入不一致', trigger: ['blur', 'password-input'] }
  ],

}

function handlePasswordInput() { }

// 添加用户函数
function addUser() {
  userValue.value = userValueInit()
  showModal.value = true
  modalTitle.value = '新建用户'

}

function cancleBtn() {
  showModal.value = false
  userValue.value = {}
}

function editUser() {
  formRef.value.validate((err) => {
    if (!err) {
      let reqMethod
      let apiAddr

      switch (modalTitle.value) {
        case '新建用户':
          reqMethod = 'POST'
          apiAddr = '/api/user'

          break;
        case '编辑用户':
          reqMethod = 'PUT'
          apiAddr = '/api/user/' + userValue.value.id

          break;
        default:
          break;
      }

      console.log(userValue.value)
      proxy.$http({
        method: reqMethod,
        url: apiAddr,
        // data: userValue.value
        data: userValue.value
      })
        .then(function (response) {
          message.destroyAll();
          message.success(response.data.msg, { duration: 2000 })
          // 关闭对话框，刷新页面
          showModal.value = false
          getUserInfo(page.value, pageSize.value)
        })

        .catch(function (error) {
          console.error(error);
          message.destroyAll();
          message.error("请求失败，请查看网络是否连接", { duration: 2000 })
        })


    } else {
      message.error(err);
    }
  })



}



//操作列按钮
const tableBtns = [
  {
    text: "编辑",
    type: "primary",
    click(row) {
      // modalValue.value = toRaw(row)
      // console.log(toRaw(row))
      showModal.value = true
      modalTitle.value = '编辑用户'
      //发起网络请求，获取单个用户详细信息
      proxy.$http.get(`/api/user/${row.id}`).then(response => {
        console.log(response)
        if (response.status != 200) {
          message.error(response.data.msg)
          return
        }
        userValue.value = response.data.user
      }).catch(err => {
        message.error(err)
      })

    },
  },
  {
    text: "删除",
    type: "error",
    click(row) {
      // console.log(row)
      dialog.error({
        title: '删除用户',
        content: '是否删除用户，已删除的用户无法找回！',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          // message.success('我就知道')
          proxy.$http.delete(`/api/user/${row.id}`).then(response => {
            console.log(response)
            if (response.status != 204) {
              message.error(response.data.msg)
              return
            }
            message.success("删除成功")
            getUserInfo(page.value, pageSize.value)
          }).catch(err => {
            message.error(err)
          })

        },
        onNegativeClick: () => {
          // message.error('不确定')
        }
      })

    },
  },
];
// 角色
const roleOptions = ref([
  {
    label: "超级管理员",
    value: 1,
    type: 'info'
  },
  {
    label: "操作员",
    value: 2,
    type: 'success'
  }
])
//定义表格列
const columns = [
  {
    type: "selection",
  },
  {
    title: "账号",
    key: "user",
    align: "center"
  },
  {
    title: "姓名",
    key: "name",
    align: "center",
  },
  {
    title: "角色",
    key: "role",
    align: "center",
    render(row) {
      let roleName = ''
      let type = ''
      roleOptions.value.map((roleItem) => {
        if (roleItem.value == row.role) {
          roleName = roleItem.label
          type = roleItem.type
        }
      })
      return h("div", null, [
        h(
          NTag,
          {
            type: type,
          },
          { default: () => roleName }
        )
      ]);
    }
  },
  {
    title: "手机号码",
    key: "phone",
    align: "center",
  },
  {
    title: "邮箱",
    key: "email",
    align: "center",
  },
  {
    title: "状态",
    key: "state",
    align: "center",
    render(row) {
      if (row.status == 1) {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              processing: true,
              type: "success",
              style: "margin-right:5px",
            },
            null
          ),
          "正常",
        ]);
      } else {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              type: "error",
              style: "margin-right:5px",
            },
            null
          ),
          "禁用",
        ]);
      }
    },
  },
  {
    title: "创建时间",
    align: "center",
    render(row){
      return h(
        'span',null, formateData.formateDate(row.createdAt)
      )
    }
  },
  {
    title: "操作",
    align: "center",
    render(row) {
      return h(
        NSpace,
        {
          justify: "center",
        },
        {
          default: () =>
            tableBtns.map((tagKey) => {
              return h(
                NButton,
                {
                  type: tagKey.type,
                  size: "small",
                  onClick: () => tagKey.click(row)
                },
                { default: () => tagKey.text }
              );
            }),
        }
      );
    },
    // render(row) {
    //   return h(NSpace,
    //     {
    //       justify: "center",
    //     }, {
    //     default: () => [
    //       h(
    //         NButton,
    //         {
    //           type: "primary",
    //           size: "small",
    //         },
    //         {
    //           default: () => "编辑"
    //         }
    //       ),
    //       h(
    //         NPopconfirm,
    //         null,
    //         // {
    //         //   default: () => "删除"
    //         // }
    //         {
    //           default: () => {
    //             return h('template', '#trigger', {
    //               default: () => [
    //                 h(
    //                   NButton,
    //                   {
    //                     type: "error",
    //                     size: "small",
    //                   },
    //                   {
    //                     default: () => "删除"
    //                   }
    //                 ),
    //                 h(
    //                   'span',
    //                   null,
    //                   {
    //                     default: () => "一切都将一去杳然，任何人都无法将其捕获。"
    //                   }
    //                 )
    //               ]
    //             })
    //           }
    //         }

    //       ),
    //     ]
    //   }
    //   );
    // },
  },
];

const data = ref([]);

const checkedRowKeys = ref([]);

// 获取分页用户信息的函数
function getUserInfo(pagenum, pagesize) {
  proxy.$http
    .get("/api/user/list", {
      params: {
        page: pagenum - 1,
        pagesize: pagesize,
      },
    })
    .then(function (response) {
      console.log(response)
      if (response.status != 200) {
        message.error(response.data.msg);
        return;
      }
       if (response.data.users) {
        data.value = response.data.users;
      } else {
        data.value = []
      }

      // data.value = response.data.users;
      total.value = response.data.total;

      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}

function handleCheck(rowKeys) {
  checkedRowKeys.value = rowKeys;
}

//查询用户
function searchUser() {
  console.log("查询用户");
}

//全选
let checkedAll = ref(false);
function handleCheckedChange(checked) {
  checkedAll.value = checked;
}

// 分页部分
const page = ref(1);
const pageSize = ref(10);
let total = ref(null);
const pageGroup = [10, 20, 30, 50, 100]

const pageCount = computed(() => {
  return Math.ceil(total.value / pageSize.value);
});

// 翻页回调
function PageChange(p) {
  page.value = p;
  // console.log(p);
  getUserInfo(p, pageSize.value);
}
// 设置吗每页显示数量回调
function pageSizeChange(psize) {
  pageSize.value = psize;
  page.value = 1
  getUserInfo(page.value, psize);
}

onBeforeMount(() => {
  getUserInfo(page.value, pageSize.value)
});
</script>
